package com.ruoyi.service;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.ruoyi.ChatRequest;
import com.ruoyi.config.DeepSeekConfig;
import com.ruoyi.medol.Message;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import com.alibaba.fastjson2.JSON;

import java.io.*;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Scanner;



@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekService {
    private final DeepSeekConfig config;
    private final WebClient.Builder webClientBuilder;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public void startInteractiveChat() {
        try (Scanner scanner = new Scanner(System.in);
             PrintWriter fileWriter = new PrintWriter(new FileWriter("conversation.txt", true))) {

            while (true) {
                System.out.print("\n请输入您的问题 (输入 q 退出): ");
                String question = scanner.nextLine().trim();

                if ("q".equalsIgnoreCase(question)) {
                    System.out.println("程序已退出");
                    break;
                }

                // 保存问题
                saveToFile(fileWriter, question, true);

                // 发起对话请求
                Flux<String> responseFlux = sendChatRequest(question);

                StringBuilder fullResponse = new StringBuilder();
                responseFlux
                        .doOnNext(chunk -> {
                            System.out.print(chunk);
                            fullResponse.append(chunk);
                        })
                        .doOnComplete(() -> {
                            // 保存完整回复
                            saveToFile(fileWriter, fullResponse.toString(), false);
                            System.out.println("\n----------------------------------------");
                            fileWriter.println("\n----------------------------------------");
                            fileWriter.flush();
                        })
                        .blockLast();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Flux<String> handleChatWebSocket(String question) {
        return sendChatRequest(question)
                .doOnNext(response -> log.info("发送响应: {}", response))
                .onErrorResume(e -> {
                    log.error("WebSocket通信错误: {}", e.getMessage());
                    return Flux.just("抱歉，服务器处理请求时发生错误，请稍后重试。");
                });
    }

    public Flux<String> sendChatRequest(String question) {
        ChatRequest request = new ChatRequest();
        Message userMessage = new Message();
        userMessage.setRole("user");
        userMessage.setContent(question);
        request.setMessages(Collections.singletonList(userMessage));

        log.info("发送请求到: {}", config.getApiUrl());

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

        Flux<String> flix = null;
            String jsonBody = JSON.toJSONString(request);
            Request okRequest = new Request.Builder()
                    .url(config.getApiUrl())
                    .post(RequestBody.create(jsonBody, MediaType.get("application/json")))
                    .header("Authorization", "Bearer " + config.getApiKey())
                    .header("Content-Type", "application/json")
                    .build();

        try (Response response = client.newCall(okRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code() + " - " + response.message());
            }

            if (response.body() == null) {
                throw new IOException("响应体为空");
            }

            String responseBody = response.body().string();
            System.out.println("原始响应: " + responseBody); // 打印原始响应，检查格式

            // 检查是否是流式响应（如 "[DONE]" 或 SSE 格式）
            if (responseBody.trim().equals("[DONE]")) {
                System.out.println("流式响应结束");
                return null;
            }

            // 尝试解析 JSON
            try {
                // 假设返回类似 OpenAI 的格式：
                // {"choices":[{"message":{"content":"Hello!"}}]}
                // 或流式格式：{"choices":[{"delta":{"content":"Hi"}}]}
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(responseBody);

                if (rootNode.has("choices")) {
                    JsonNode choices = rootNode.get("choices");
                    if (choices.isArray() && choices.size() > 0) {
                        JsonNode firstChoice = choices.get(0);
                        if (firstChoice.has("message") && firstChoice.get("message").has("content")) {
                            String content = firstChoice.get("message").get("content").asText();
                            System.out.println("AI 回复: " + content);
                            flix = Flux.just(content);
                        } else if (firstChoice.has("delta") && firstChoice.get("delta").has("content")) {
                            String content = firstChoice.get("delta").get("content").asText();
                            System.out.println("AI 流式回复: " + content);
                        } else {
                            System.out.println("无法解析 choices 结构: " + firstChoice);
                        }
                    }
                } else if (rootNode.has("error")) {
                    String errorMsg = rootNode.get("error").get("message").asText();
                    throw new IOException("API 返回错误: " + errorMsg);
                } else {
                    System.out.println("未知响应格式: " + responseBody);
                }
            } catch (JsonProcessingException e) {
                throw new IOException("JSON 解析失败: " + e.getMessage() + "\n原始响应: " + responseBody);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return flix;

    }

    private void saveToFile(PrintWriter fileWriter, String content, boolean isQuestion) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        if (isQuestion) {
            fileWriter.printf("\n[%s] Question:\n%s\n\n[%s] Answer:\n", timestamp, content, timestamp);
        } else {
            fileWriter.print(content);
        }
        fileWriter.flush();
    }
}

